#include "EventLoop.hpp"
#include "TcpServer.hpp"
#include "ThreadPool.h"

#include <cstdlib>
#include <iostream>
#include <sys/epoll.h>
#include <unistd.h>
using std::cout;
using std::endl;



class Mytask{
public:
    Mytask(const string & msg, wd::TcpConnectionptr conn)
    :_msg(msg)
    ,_conn(conn)
    {
    }
    //子线程入口函数
    void process(){
        cout << "Mytask::process is running" << endl;
        string response = _msg;
        _conn->sendInLoop(response);
    }

private:
    string _msg;
    wd::TcpConnectionptr _conn;
};




class EchoServer{
public:
    EchoServer(int port, const string ip, int threadNum, int queSize)
    :_threadpool(threadNum, queSize)
    ,_server(port, ip)
    {
        printf("EchoServer\n");
        using namespace std::placeholders;
        _server.setAllCallbacks(
            std::bind(&EchoServer::onConnection, this, _1),
            std::bind(&EchoServer::onMessage,this, _1),
            std::bind(&EchoServer::onClose, this, _1));
    }

    void start(){
        _threadpool.start();
        _server.start();
    }


    void stop(){
        _threadpool.stop();
        _server.stop();
    }

private:
    void onConnection(wd::TcpConnectionptr tcpconn){
        printf("a new clienfd connected.\n");
    }
    
    void onMessage(wd::TcpConnectionptr tcpconn){
        string msg = tcpconn->receive();
        cout << "receive msg:"<< msg << endl;
        //此处为收到客户端信息后要执行的业务处理,交给子线程处理
        Mytask task(msg,tcpconn);
        _threadpool.addTask(std::bind(&Mytask::process, task));
    
    }
    void onClose(wd::TcpConnectionptr tcpconn){
        printf("a clienfd closed.\n");
    }

private:
    ThreadPool _threadpool;
    wd::TcpServer _server;
};



int main()
{
    EchoServer server(12345,"0.0.0.0",4,10);
    server.start();
    
    //sleep(60);
    //server.stop();

    return 0;
}

